package dao

import (
	"gorm.io/gorm"
	"learn/global"
	"learn/respository/db/model"
	"sync"
)

var (
	pmsBrandDaoInstance *PmsBrandDao
	once                sync.Once
)

type PmsBrandDao struct {
	*gorm.DB
}

func NewPmsBrandDao() *PmsBrandDao {
	once.Do(func() {
		pmsBrandDaoInstance = &PmsBrandDao{
			global.DB,
		}
	})
	return pmsBrandDaoInstance
}

func (dao *PmsBrandDao) Create(pmsBrand *model.PmsBrand) (err error) {
	err = dao.Model(&model.PmsBrand{}).Create(&pmsBrand).Error
	return
}

func (dao *PmsBrandDao) PageList(keywords string, showStatus, pageNum, pageSize int) (pmsBrandList []model.PmsBrand, total *int64, err error) {

	var num int64

	countErr := dao.Model(&model.PmsBrand{}).
		Where("(name like ? or first_letter like ?) and  show_status = ?", "%"+keywords+"%", "%"+keywords+"%", showStatus).Where("sort in ?", []int{1, 200}).Count(&num).Error
	if countErr != nil {
		return nil, nil, countErr
	}
	dataErr := dao.Model(&model.PmsBrand{}).Scopes(Paginate(pageNum, pageSize)).Where("(name like ? or first_letter like ?) and  show_status = ?", "%"+keywords+"%", "%"+keywords+"%", showStatus).
		Order("id desc,name").Find(&pmsBrandList).Error
	if dataErr != nil {
		return nil, nil, dataErr
	}

	return pmsBrandList, &num, nil
}
